\documentclass[11pt]{report}
\title{Predator Prey Model\let\thefootnote\relax\footnotetext{When writing this report, a lot of emphasis was put on interactivity, so, a reader would benefit from reading an electronic version (PDF) rather than a paper one}}
\author{Matt Cole\\ Tom Catling\\ Simon Gardner\\ Milena Pawlik\\ Dmitry Tsigelnitskiy\\ Jorge Moreira\\ Chen Shen}
\date{November 2011}

\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{tikz}
\usepackage[margin=3.2cm]{geometry}
\usepackage{float}
\usepackage{verbatim} 
\usepackage{pict2e}
\usepackage[pdftex]{hyperref}
\usepackage{subfig}
%%%%% Remove URL link boxes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\usepackage{times}

%%%%% Code Constraints %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{listings}
 \usepackage{courier}
%\lstset{
\lstset{columns=fullflexible,
language=Java,
%captionpos=b,
basicstyle=\footnotesize,
keywordstyle=\bfseries\ttfamily\color[rgb]{0,0,1},
identifierstyle=\ttfamily,
commentstyle=\color[rgb]{0.133,0.545,0.133},
stringstyle=\ttfamily\color[rgb]{0.627,0.126,0.941},
showstringspaces=false,
%basicstyle=\small,
numberstyle=\footnotesize,
numbers=left,
stepnumber=1,
numbersep=5pt,
tabsize=1,
breaklines=true,
%prebreak = \raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}},
breakatwhitespace=false,
aboveskip={1.5\baselineskip},
columns=fixed,
%upquote=true,
extendedchars=true,
%frame=bottomline,
inputencoding=utf8
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}

\usetikzlibrary{shapes,arrows}


\tikzstyle{block} = [rectangle, draw, fill=blue!20, 
    text width=5em, text centered, rounded corners, minimum height=4em]
\tikzstyle{line} = [draw, -latex']

\maketitle

%\begin{abstract}
%\end{abstract}


\tableofcontents
\thispagestyle{empty}

\chapter{Introduction}
\setcounter{page}{1}

% i just wrote this to get the report started - feel free to change or add to it
This project involved writing a computational simulation of a predator-prey model. The focus of the task was to produce an efficient algorithm and a readable extendible code base. This was  done by making use of a number of key development tools and employing a good set of programming practices throughout. The problem was as follows:
\begin{itemize}
\item An island represented by a rectangular domain, where every grid point is either land or water
\item Density of prey (hares) and predators (pumas) are changing with time depending on parameters $r$,$a$,$b$ $m$, $k$, $l$.\footnote{Where $r$ is prey birth rate, $a$ is predation rate, $b$ is predator birth rate, $m$ is predator death rate, $k$ is prey diffusion rate, $l$ is predator diffusion rate}
\item differential equation governing changes in population density where H is prey population density, P is predator population density, ${\Delta}t$ is discreet timestep size:
\begin{equation*}
H_{ij}^{new}=H_{ij}^{old} + {\Delta}t(rH_{ij}^{old}+aH_{ij}^{old}P_{ij}^{old} + k((H_{i+1j}^{old} + H_{i-1j}^{old} + H_{ij+1}^{old} + H_{ij-1}^{old})-N_{ij}H_{ij}^{old})
\end{equation*}
\begin{equation*}
P_{ij}^{new}=P_{ij}^{old} + {\Delta}t(bH_{ij}^{old}P_{ij}^{old}-mP_{ij}^{old} + l((P_{i+1j}^{old} + P_{i-1j}^{old} + P_{ij+1}^{old} + P_{ij-1}^{old})-N_{ij}P_{ij}^{old})
\end{equation*}

\item Aim to simulate a grid up to 2000x2000 points updating populations for a certain time.
\end{itemize}

% i just wrote this to get the report started - feel free to change or add to it

We designed the program in such a way as to take advantage of Java's object-orientated, modular nature. Due to the large size of our group we also decided to incorporate a GUI. The program can still be run from the command line, as in some situations (ssh) a GUI is not available.\newline{}

There is always some compromise between readability (object oriented design) and performance in OO coding, and we tried to maintain a reasonable balance when designing our code. We made best use of class structure whilst still keeping our implementation of the given algorithm as efficient as possible.\newline{}

The predator prey algorithm implemented in this project crudely models the interaction between population densities of different animals, specifically hares and pumas. Each population has a self-interaction coefficient (birth for Hares, death for Pumas) and a coefficient describing how it interacts with other species' populations. \newline{}

These populations exist in a 'world' consisting of land and water and are also able to diffuse across land squares with a rate determined by a diffusion coefficient. Thus, each population has N+1 coefficients which determine its behaviour, where N is the number of animals.

\chapter{Design \& Implementation}
   \section{Code}
      \subsection{Structure} %simon (dmitry to make flowchart)
      %not sure if this is quite right but a first go at the code structure explanaion
          All code was written with Java. Doing so gave us easy access to numerous tools such as Javadoc and Swing for creating GUIs, the main advantage for most of us was the familiarity of working with object oriented code design. Object orientation provided us with the opportunity to design the central workings of the code with extensive extendibility, leaving just the user interface specifically designed for the problem at hand.
\subsubsection{Classes Flow Chart}
\begin{center}
\begin{tikzpicture}[node distance = 3.2cm, auto]

\node [block]  (Animal) {Animal\\ \ref{sec:Animal}};

\node [block, right of=Animal] (GridAlg) {GridAlg \\ \ref{sec:GridAlg}};

\node [block, right of=GridAlg] (MapReader) {MapReader\\ \ref{sec:MapReader}};

\node [block, right of=MapReader] (Output) {Output\\ \ref{sec:Output}};

\node [block, below of=GridAlg] (InputFrame) {GUI\\ \ref{sec:GUI}};

\node [block, below of=MapReader] (PredPrey) {PredPrey\\ \ref{sec:PredPrey}};


\path [line] (Animal) -- (PredPrey);

\path [line] (GridAlg) -- (PredPrey);

\path [line] (MapReader) -- (PredPrey);

\path [line] (Output) -- (PredPrey);

\draw[->] (InputFrame) -- (PredPrey);
\draw[->] (PredPrey) -- (InputFrame);
 
\end{tikzpicture}
\end{center}

\subsubsection{Animal}
\label{sec:Animal}
The Animal class holds the information about the animal; it's density distribution and how it is updated relating to other animals.
Its methods are called called from the PredPrey class where which passes it the values taken from the GUI or input file. Discussion of the implementation of the main algorithm can be found in section \ref{sec:Algorithm}
\subsubsection{GridAlg}
\label{sec:GridAlg}
This class governs methods for updating the animal densities across the grid. The constructor takes the array of animals passed after creation in the PredPrey class and the 2 dimensional array of neighbours passed from the MapReader class. Upon creation, the GridAlg class initialises the densities of each animal in each grid cell to a uniformly distributed random number between 0 and 5, changing this range are only seen to change the scale of the simulation. A couple of different methods of updating the grid are held in the class, these is discussed further in subsection \ref{sec:Algorithm}.


\subsubsection{MapReader}
\label{sec:MapReader}
The MapReader class is responsible for reading the file which holds where the land and water are and outputs an array holding the neighbours of all the land cells, this is discussed further in section \ref{Input_Output}.

\subsubsection{Output}
\label{sec:Output}
The output class is sent density distributions of the animals and from that calculates and outputs the average density as well as an image of the density distribution. The format and creation of these files is discussed further in section \ref{Input_Output}

\subsubsection{GUI}
\label{sec:GUI}
This class is responsible for displaying a GUI for a user to input parameters of the simulation discussed further in section \ref{GUI}


\subsubsection{PredPrey}
\label{sec:PredPrey}
 A main class, PredPrey, governs the creation of occurrences of all of the other classes as required. When running the program from the command line there is an option to run with or without a GUI, this is determined by whether the input file names are given as arguments. If the arguments are passed, the input parameters are read from the file, if they are not then the user can input them in themselves via the GUI.

\subsection{Algorithm} %matt
      \label{sec:Algorithm}
      The equations shown in the problem Model are specific to Hares and Pumas located in the cells of the world grid. Out initial approach was to write a computational algorithm that simply iterated the equations for the density arrays of the two animals. The next stage in the development was creating an abstract Animal class, for which subclasses provided the implementation of the kernel specific to that animal. It was soon realised that this abstraction could be removed, and the problem generalised even further resulting in the current algorithm: A general Animal class is used to represent any species present in the world. Instances of Animal are created at runtime for all such species. These objects contain all of the information about the animal, most importantly: 
\begin{lstlisting}[numbers=none, language=Java,caption=The fundamental fields of the animal class.]
// The density of the animal in each cell
double[][] densities
// The diffusion rate of the animal     
double diffusionRate
// The coeficients controling the effect of other animals on the animal
double diffCo[] 
\end{lstlisting}

      To illustrate more clearly what values diffusionRate and diffCo[] take, they are shown for the simple hare puma case that was used for the entirety of testing.
      
\begin{lstlisting}[numbers=none, language=Java,caption=Behavioural coefficients for the hare instance of animal.]
diffusionRate = k
diffCo[0] = r		 // How hares effects the hare
diffCo[1] = -a		// How pumas effects the hare
\end{lstlisting} \begin{lstlisting}[numbers=none, language=Java,caption=Behavioural coefficients for the puma instance of animal.]
diffusionRate = l
diffCo[0] = b			 // How hares effect the puma
diffCo[1] = -m			// How pumas effect the puma
\end{lstlisting}

The governing class (PredPrey) creates an array of Animals, passing each their diffusion rate, and the array diffCo dictating how the of the other animals effect them. Armed with these tools, the Animal objects are able to iterate the equations shown in the model themselves. As long as the constants governing the effect of each animal on others are known, the size of the array of Animals can be increased to as many as desired. At each time step, the code loops over the animals, invoking the calcNextDensity() method. Part of this method is shown in listing 3.4.

\begin{lstlisting}[numbers=none, language=Java,caption=The key part of the computational kernel within animal - called when the density for a single cell is to be updated to the next time step.]
// Loop over the total number of animals/behavioral coefficients.
for (int k = 0; k < animals.length; k++) {
			
		/*
		Add the contribution to the new density depending on the weather 
		the animal is this or not.
		*/
		if (animals[k] == this) {
				newDensity += dt*getDiffCo()[k]*oldDensity;
		} 
		else {
				newDensity += dt*getDiffCo()[k]*animals[k].getDensity(y, x)*oldDensity;
		}
}

// Add the contribution based on the animals diffusion rate
...
...
...
\end{lstlisting} 

The GridAlg class controls the order in which the cells are updated which is an important feature of the algorithm. In the final version, all of the animals and all cells are
updated simultaneously. This is implemented by temporarily storing the results of a time step
and not actually applying the new densities to the system until all other calculations are
complete. In doing this, it is ensured that the all densities used in calculations within the kernel are from the same time step.

\input{Input_Output} %milena
\label{Input_Output}
      
\input{GUI} %dmitry
\label{GUI}

   
   \section{Tools}
   
   	 
	 \subsection{IDE}
	 
	 IDE stands for `Integrated Development Environment', which is widely used in modern program development, especially in object-oriented projects. Because Java is a completely object-oriented programming language, IDEs became an indispensable tool during this project.
Most of the group members used the Eclipse IDE to develop the program. Eclipse provides many useful features that aid the development process including an extensive debugger, 
realtime error checking, comprehensive autocompleting and support for JUnit testing. In addition to Eclipse a number of other tools were utilised, details of which can be found in the following sections.\newline{}

Compared to Eclipse, Netbeans is a new IDE for Java developed by Sun, which provides more powerful debugging and performance scanning tools. The performance analysis section was held on Netbeans IDE by Netbeans Profiler.  
   %matt
     
     
      \subsection{SVN} %matt
      
	We chose to host the SVN repository using a Google Code project. The home page can be found at \href{http://code.google.com/p/ps-predator-prey/}{http://code.google.com/p/ps-predator-prey/}. Doing so allowed us to make use of the many excellent tools that are available for managing such projects; the most obvious example being the ability to quickly and easily browse all of the revisions from r1 current via the web interface.  The fact that the code was hosted externally on a 24/h server meant that it could be accessed from anywhere at any time. There was also no issue with compatibility: Some of the group members opted to use the SVN Eclipse plugin that interfaces seamlessly with the Google Code while others chose to use the more traditional approach of checking code in and out via the command line. Another invaluable feature was the ability to compare side by side any and all changes between revisions. 
	 This feature is compatible with all text files, and so also proved useful for the group editing of latex files.	   
 
      
      \subsection{Ant File} %tom, Jorge 
To automate the building of the software, we have coded an Ant file using the XML language. The Ant file contains the appropriate sections that ensures compilation uses the correct files in the right packages. In order to maintain portability, we included a lib/ directory that contains libraries necessary to the Ant program, so it needs not search the local file system. The scripts also produces a .jar file containing the whole project for easy transportation.  
 
      \subsection{Unit Testing} %jorge
      Every class of the project form a functional unit according to the design elaborated at the beginning of the project. In order to ensure the software's good functioning and correct behaviour, all classes have been tested using the Java JUnit framework with test cases to tackle programming errors and code bugs.

The libraries necessary to the tests are thus accessed from the test cases using Java import statements and extending the TestCase superclass in the class declaration:
\begin{lstlisting}[language=Java,caption= Test case headers, numbers=none]
import org.junit.Before;
import org.junit.Test;
import junit.framework.TestCase;

public class TestAnimal extends TestCase {
...
\end{lstlisting}

The test cases, for each class, follow the normal directives in use for Unit testing with JUnit. The most relevant methods were submitted to thorough tests, where their properties, return values and correct functioning were evaluated by comparing the actual results they provide with the expected ones. These procedures were implemented by test methods in each test case using the format required by the JUnit standards. 

Every test case includes a setup() method that builds the initial object and its different parameters. Directives like @Before and @Test for every method declaration were thus inserted in the code were appropriate. The functioning of a method is then assessed comparing the expected results with the actual ones with JUnit testing methods such as AssertEquals(), AssertNotNull(), etc...

\begin{lstlisting}[language=Java,caption= Use of JUnit directives in test cases, numbers=none]
@Before
public void setUp() {
    ...
    testAnimal = new Animal(numbAnimals);
    testAnimal.setName("Puma");
    ...
@Test
public void testAnimal() {
    assertNotNull(testAnimal);
    assertNotNull(testAnimal2);
} 
...
\end{lstlisting}

Where possible and where the tests were failing, we corrected and bettered the code until all tests passed correctly. We have employed several different methods and tools to debug the code, mainly with Eclipse IDE's debugger and JDB (Java Debugger) at the command line, that enabled us to verify the variables in use in classes and methods are holding the correct desired values during runtime. We have in this manner corrected many mistakes and wrong operations until the software was performing as expected. We also have used certain programming techniques such as Test Driven Development, unfortunately in just a few classes, although the procedure would deserve more time and practice to achieve a reasonable degree of maturity and efficiency to prove a powerful tool. 

\chapter{Results}
After the code was completed and was outputting sensible ppm files like the ones shown previously, we needed to confirm that the density profiles were behaving correctly. The most obvious way of doing this was to plot the mean densities over time for both of the animals. This plot is shown in figure 4.1 for the default parameters given in problem specification. As expected both animals start of with an average density of 2.5 (after having initialised the densities with uniform random distributions between 0 and 5). As the pumas begin to eat the hares, the predator densities increase, corresponding to a decrease in the density of hares.
The pumas eventually eat all of hares in their areas, and start to die off, corresponding to an increase in hare population. The hares then begin to spread, and the cycle repeats itself.

	\section{Output Analysis}
	\begin{figure}[H]
   
   \input{figs/density}
   \caption{Population density vs. time for Hares and Pumas. This periodic behaviour is typical of predator-prey interactions.}
   \end{figure}

\input{Performance_Analysis}

\chapter{Conclusions} %everyone

	The Google Code SVN, combined with the ability to compile and run Java code on any platform, provided a universal code base that could be accessed from anywhere at any time.  
	
We chose to write the program with a generalised algorithm, such that it could be easily extended to handle more animals. While this results in slight decrease in efficiency over a more primitive less extendible alternative, it was felt that it offered a solution that was more in line with good programming practices.

The GUI was not necessary for this task, however it did provide a more user friendly experience and the ability to range over parameters. Possible improvements exist; animations of the island could be output to the GUI, and the option to run performance tests could be added.
  
The group performed well and achieved with success the task proposed at the beginning of the project. The solution is a fully working piece of software that models the diffusion of pumas and hares on a grid over time. The group has also been able to complete tests and analysis of the results obtained from the software and to plot these results on a series of graphs that visualise the behaviour of the model in time.
\end{document}
